package com.software.car.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import com.software.car.api.FileSavaService;
import com.software.car.common.enums.ResultEnum;
import com.software.car.common.utils.CommonResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.List;

/**
 *
 * 图片controller
 *
 * @Author 魔法はまだ解けない
 * @Date 2021/2/9
 */
@RestController
public class ImgController {

    Logger logger = LoggerFactory.getLogger(getClass());
    @Autowired
    FileSavaService fileSavaService;

    /**
     *
     * 上传文件
     *
     * @param multipartFile
     * @return      文件名称
     */
    @PostMapping("/fileUpload")
    @PreAuthorize("hasAnyRole('ROLE_SUPER_ADMINISTER','ROLE_ADMINISTER')")
    public CommonResult fileUpload(@RequestParam(value = "file") MultipartFile multipartFile) throws IOException {
        logger.info("执行——ImgController——路径：/fileUpload");
        logger.info("执行方法——fileUpload()方法");
        if (multipartFile.isEmpty()) {
            return CommonResult.fail(ResultEnum.FILE_UPLOAD);
        }
        String name = fileSavaService.uploadFile(multipartFile);
        return CommonResult.success(name);
    }
    /**
     *
     * 上传文件
     *
     * @param multipartFile
     * @return      文件名称
     */
    @PostMapping("/upload")
    @PreAuthorize("hasAnyRole('ROLE_SUPER_ADMINISTER','ROLE_ADMINISTER')")
    public CommonResult fileUploadNew(@RequestParam(value = "file") MultipartFile multipartFile) throws IOException {
        logger.info("执行——ImgController——路径：/fileUpload");
        logger.info("执行方法——fileUpload()方法");
        if (multipartFile.isEmpty()) {
            return CommonResult.fail(ResultEnum.FILE_UPLOAD);
        }
        String name = fileSavaService.uploadFileNew(multipartFile);
        return CommonResult.success(name);
    }
    /**
     * 下载接口
     * @param flag
     * @param response
     * @return
     */
    @GetMapping("/photoload/{flag}")
    public void getFiles(@PathVariable String flag, HttpServletResponse response) {
        OutputStream os;  // 新建一个输出流对象
        String basePath = System.getProperty("user.dir") + "/src/main/resources/files/";  // 定于文件上传的根路径
        List<String> fileNames = FileUtil.listFileNames(basePath);  // 获取所有的文件名称
        String fileName = fileNames.stream().filter(name -> name.contains(flag)).findAny().orElse("");  // 找到跟参数一致的文件
        try {
            if (StrUtil.isNotEmpty(fileName)) {
                response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
                response.setContentType("application/octet-stream");
                byte[] bytes = FileUtil.readBytes(basePath + fileName);  // 通过文件的路径读取文件字节流
                os = response.getOutputStream();   // 通过输出流返回文件
                os.write(bytes);
                os.flush();
                os.close();
            }
        } catch (Exception e) {
            System.out.println("文件下载失败");
        }
    }

    /**
     * 下载文件
     * @param fileName  文件名
     * @param type      文件下载类型
     * @param response
     * @return  操作成功
     * @throws IOException
     */
    @GetMapping("/public")
    public void getFile(@RequestParam(name = "fileName") String fileName,
                                @RequestParam(name = "type",required = false)Integer type,
                                HttpServletResponse response) throws IOException {
        logger.info("执行——ImgController——路径：/public");
        logger.info("执行方法——getFile()方法");
        /**
         * 设置文件名
         */
        response.addHeader("Content-Disposition", "attachment;fileName=" + fileName);
        if (type != null) {

            /**
             * 设置保存方式为下载
             */
            response.setContentType("application/force-download");
        }
        fileSavaService.getFile(fileName,response);
    }
}
